package com.wuwei.elearning.question.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wuwei.elearning.question.domain.Collect;
import com.wuwei.elearning.question.mapper.CollectMapper;
import com.wuwei.elearning.question.service.CollectService;
import com.wuwei.elearning.setting.domain.User;
import com.wuwei.elearning.setting.mapper.UserMapper;
import com.wuwei.elearning.utils.result.Result;
import com.wuwei.elearning.utils.token.TokenUtil;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wuwei
 * @since 2024-03-28
 */
@RestController
@RequestMapping("/elearning/collect")
@CrossOrigin
public class CollectController {

    @Resource
    private UserMapper userMapper;

    @Resource
    private CollectService collectService;

    @Resource
    private CollectMapper collectMapper;


    /**
     * 用户点击收藏或取消收藏，则会添加
     * @param questionId
     * @param collectFlag
     * @return
     */
    @PutMapping("updateCollect/{questionId}/{collectFlag}/{selectedId}")
    public Result<String> updateCollect(@PathVariable("questionId") Long questionId, @PathVariable("collectFlag") Integer collectFlag,
                                         @PathVariable("selectedId") Long selectedId, HttpServletRequest request){
        /**
         * 先去查询数据库中有无该记录，如果有则进行修改，如果无则新增
         */
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);

        collectService.updateCollect(account,collectFlag,questionId,selectedId);


        return Result.ok("用户收藏记录更新成功!");
    }

    @GetMapping("checkCollect/{questionId}")
    public Result<String> checkCollect(@PathVariable("questionId") Long questionId,HttpServletRequest request){
        String token = request.getHeader("Authorization");
        Long account = TokenUtil.getAccountFromToken(token);

        LambdaQueryWrapper<Collect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Collect::getQuestionId,questionId)
                .eq(Collect::getUserAccount,account);
        Long count = collectMapper.selectCount(queryWrapper);
        if (count==1) {
            return Result.ok("收藏过");
        } else if (count==0){
            return Result.ok("未收藏");
        } else {
            return Result.fail("数据库查询失败！user_id和question_id字段联合查询最多只能由一条记录！");
        }
    }

}

